<template>
  <div class="dashboard-container">
    <h1 style="text-align: center">顾客管理</h1>

    <el-dialog title="拉黑" :visible.sync="blackListButtonController" width="30%" @close="closeBlackList('ruleForm')">
      <el-form :rules="Customers" label-width="20%" :model="blackList" ref="ruleForm">
        <el-form-item label="顾客ID" prop="customerId">
          <el-input v-model="blackList.customerId" maxlength="11" show-word-limit style="width: 80%" clearable placeholder="请输入顾客ID"/>
        </el-form-item>
<!--        <el-form-item label="失信程度" prop="roomTypeId">-->
<!--          <el-select v-model="blackList.state" clearable placeholder="失信程度" style="width: 80%" >-->
<!--            <el-option-->
<!--              v-for="item in stateList"-->
<!--              :key="item.value"-->
<!--              :label="item.label"-->
<!--              :value="item.value">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="blackList.remark" maxlength="100" show-word-limit style="width: 80%" clearable placeholder="请输入备注"/>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" plain @click="addBlackList('ruleForm')">确 定</el-button>
        <el-button plain @click="closeBlackList('ruleForm')">取 消</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="新增"
      :visible.sync="addButtonController"
      width="50%"
      @close="closeCustomer('ruleForm')"
    >
      <el-form label-width="20%" :model="addOrUpdateList" :rules="Customers" ref="ruleForm">
        <el-form-item label="顾客名称" prop="customerName">
          <el-input v-model="addOrUpdateList.customerName" maxlength="50" show-word-limit style="width: 80%" clearable
                    placeholder="请输入顾客名称"
          />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="addOrUpdateList.sex">
            <el-radio label="男" value="男">男</el-radio>
            <el-radio label="女" value="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="电话号码" prop="phoneNumber">
          <el-input v-model="addOrUpdateList.phoneNumber" maxlength="11"  show-word-limit style="width: 80%" clearable
                    placeholder="请输入电话号码"
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="identificationCard">
          <el-input v-model="addOrUpdateList.identificationCard"  maxlength="18" show-word-limit style="width: 80%" clearable
                    placeholder="请输入身份证号"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addOrUpdateList.remark" maxlength="100" show-word-limit style="width: 80%" clearable
                    placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="addCustomer('ruleForm')">确 定</el-button>
    <el-button @click="closeCustomer('ruleForm')">取 消</el-button>
  </span>
    </el-dialog>
    <el-button plain
               style="width:80px;margin-bottom:30px;margin-left:18% ;background-color: #cfefc6; border-radius: 8px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);"
               @click="addButton"
    >
      新增
    </el-button>

    <el-dialog
      :visible.sync="updateButtonController"
      title="修改"
      width="50%"
      @close="closeCustomer('ruleForm')"
    >
      <el-form label-width="20%" :model="addOrUpdateList" :rules="Customers" ref="ruleForm">
        <el-form-item label="顾客名称" prop="customerName">
          <el-input v-model="addOrUpdateList.customerName" maxlength="50" show-word-limit style="width: 80%" clearable
                    placeholder="请输入顾客名称"
          />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="addOrUpdateList.sex">
            <el-radio label="男" value="男">男</el-radio>
            <el-radio label="女" value="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="电话号码" prop="phoneNumber">
          <el-input v-model="addOrUpdateList.phoneNumber" maxlength="11"  show-word-limit style="width: 80%" clearable
                    placeholder="请输入电话号码"
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="identificationCard">
          <el-input v-model="addOrUpdateList.identificationCard"  maxlength="18" show-word-limit style="width: 80%" clearable
                    placeholder="请输入身份证号"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addOrUpdateList.remark" maxlength="100" show-word-limit style="width: 80%" clearable
                    placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="updateCustomer('ruleForm')">确 定</el-button>
    <el-button @click="closeCustomer('ruleForm')">取 消</el-button>

  </span>
    </el-dialog>
    <el-input
      v-model="customerName"
      placeholder="顾客名称"
      name="customerName"
      type="text"
      clearable
      style="margin-left:40px ;width: 180px"
    />

    <el-input
      v-model="phoneNumber"
      placeholder="电话号码"
      name="phoneNumber"
      type="text"
      clearable
      style="margin-left:40px ;width: 180px"
    />
    <el-input
      v-model="identificationCard"
      placeholder="身份证号"
      name="phoneNumber"
      type="text"
      clearable
      style="margin-left:40px ;width: 180px"
    />

    <el-button plain
               style="width:80px;margin-bottom:30px;margin-left:40px ;background-color: #cfefc6; border-radius: 8px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);"
               @click="selectAll"
    >
      查询
    </el-button>
    <el-button
      style="width:80px;margin-bottom:30px;margin-left:40px ;background-color: white; border-radius: 8px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);"
      @click="checkCustomer"
    >重置
    </el-button>
    <el-table :data="customerList.slice((currentPage-1)*pagesize,currentPage*pagesize)" height="659px" border style="width: 100%;margin-top: 20px"
              class="elegant-room-table"
    >
      <el-table-column align="center" fixed prop="customerId" label="顾客ID" width="180"/>
      <el-table-column align="center" fixed prop="customerName" label="顾客名称" width="180"/>
      <el-table-column align="center" fixed prop="sex" label="性别" width="120"/>
      <el-table-column align="center" fixed prop="phoneNumber" label="电话号码" width="220"/>
      <el-table-column align="center" fixed prop="identificationCard" label="身份证号" width="250"/>
      <el-table-column align="center" fixed prop="remark" label="备注" min-width="180"/>
      <el-table-column align="center" fixed label="操作" width="130">
        <template v-slot="scope">
          <el-button size="mini" round icon="el-icon-edit" @click="updateButton(scope.row)"></el-button>
          <el-button class="el-icon-warning" circle @click="blackListButton(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top:5px;margin-left: 30%;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5,8,10,15,20]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="customerList.length">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { deleteRoomType, insert1RoomType, selectAllRoomType, updateRoomType } from '@/api/roomType'
import { insertCustomer, selectAllCustomer, updateCustomer } from '@/api/customer'
import { insertBlackList1, selectAllBlackList } from '@/api/blackList'

export default {
  name: 'user',
  computed: {
    ...mapGetters([
      'userId',
      'userName',
      'roleName'
    ])
  },
  data() {
    return {
      stateList:[{
        value: '轻度失信',
        label: '轻度失信'
      }, {
        value: '中度失信',
        label: '中度失信'
      }, {
        value: '重度失信',
        label: '重度失信'
      }],
      blackList:{
        customerId:'',
        state:'',
        remark:'',
        debtMoney:'',
        debtDay:'',
        reputation:'',
      },
      customerName: '',
      phoneNumber: '',
      identificationCard: '',
      customerList: [],
      addButtonController: false,
      updateButtonController: false,
      blackListButtonController:false,
      currentPage: 1,
      currentIndex: '',
      pagesize: 10,
      addOrUpdateList: {
        customerTableId: '',
        customerId: '',
        customerName: '',
        sex: '',
        phoneNumber: '',
        identificationCard: '',
        remark: ''
      },
      Customers: {
        customerName: [
          {required: true, trigger: 'blur', message: '顾客名称不能为空'},
          {min: 2, max: 50, message: '请输入顾客名称', trigger: 'blur'}
        ],
        sex: [
          {required: true, trigger: 'blur', message: '性别不能为空'},
        ],phoneNumber: [
          {required: true, trigger: 'blur', message: '手机号不能为空'},
          {min: 11, max: 11, message: '手机号长度11个字符', trigger: 'blur'}
        ],
        identificationCard:[
          {required: true, trigger: 'blur', message: '身份证不能为空'},
          {min: 18, max: 18, message: '身份证长度18个字符', trigger: 'blur'}
        ],
        reputation: [
          { required: true, message: '请输入信誉积分', trigger: 'blur' },
          { validator: this.validateBlackListReputation, trigger: 'blur' }
        ],
      },
    }
  },
  mounted() {
    this.selectAll()
  },
  methods: {
    handleSizeChange(val) {
      this.pagesize = val;
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage= val
    },
    validateBlackListReputation(rule, value, callback) {
      if (!value || isNaN(value)) {
        callback(new Error('信誉积分必须为数字'))
      } else if (value < 0 || value > 100) {
        callback(new Error('信誉积分必须在0到100分之间'))
      } else {
        callback()
      }
    },
    blackListButton(row){
      this.blackList = {
        customerId: row.customerId,
        state: '',     // 用户选择
        remark: ''     // 用户填写
      }
      this.blackListButtonController = true
    },
    selectAll() {
      selectAllCustomer({
        customerName: this.customerName,
        phoneNumber: this.phoneNumber,
        identificationCard: this.identificationCard
      }).then(
        response => {
          console.log(response.data)
          this.customerList = response.data
          if((this.customerList.slice((this.currentPage-1)*this.pagesize,this.currentPage*this.pagesize)).length == 0){
            this.currentPage = 1
          }
        }
      )
    },
    addButton() {
      this.addOrUpdateList = {
        customerName: '',
        sex: '',
        phoneNumber: '',
        identificationCard: '',
        remark: ''
      }
      this.addButtonController = true
    },
    updateButton(row) {
      this.addOrUpdateList = {
        customerTableId: row.customerTableId,
        customerId: row.customerId,
        customerName: row.customerName,
        sex: row.sex,
        phoneNumber: row.phoneNumber,
        identificationCard: row.identificationCard,
        remark: row.remark
      }
      this.updateButtonController = true
    },
    addBlackList(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 使用 customerId 查询黑名单
          selectAllBlackList({ customerId: this.blackList.customerId }).then(response => {
            const filtered = response.data.filter(item => item.customerId === this.blackList.customerId);
            if (filtered.length > 0) {
              this.$message.warning("该顾客已在黑名单中！");
              return;
            }
            // 如果不在黑名单，则插入
            insertBlackList1({
              customerId: this.blackList.customerId,
              state: this.blackList.state,
              remark: this.blackList.remark,
              debtMoney: this.blackList.debtMoney,
              debtDay: this.blackList.debtDay,
              reputation: this.blackList.reputation,
            }).then(response => {
              this.blackListButtonController = false;
              this.$message.success("拉黑成功！");
              this.selectAll();
            });
          });
        } else {
          return false;
        }
      });
    },
    addCustomer(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          insertCustomer({
            customerName: this.addOrUpdateList.customerName,
            sex: this.addOrUpdateList.sex,
            phoneNumber: this.addOrUpdateList.phoneNumber,
            identificationCard: this.addOrUpdateList.identificationCard,
            remark: this.addOrUpdateList.remark
          }).then(
            response => {
              this.addButtonController = false
              this.$message.success('新增成功！')
              this.selectAll()
            }
          )
        } else {
          return false
        }
      })
    },
    updateCustomer(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateCustomer({
            customerTableId: this.addOrUpdateList.customerTableId,
            customerId: this.addOrUpdateList.customerId,
            customerName: this.addOrUpdateList.customerName,
            sex: this.addOrUpdateList.sex,
            phoneNumber: this.addOrUpdateList.phoneNumber,
            identificationCard: this.addOrUpdateList.identificationCard,
            remark: this.addOrUpdateList.remark
          }).then(
            response => {
              this.updateButtonController = false
              this.selectAll()
            }
          )

        } else {
          return false
        }
      })
    },
    checkCustomer() {
      this.customerName = ''
      this.phoneNumber = ''
      this.identificationCard  = ''
      this.selectAll()
    },
    closeCustomer(formName) {
      this.$refs[formName].resetFields()
      this.addButtonController = false
      this.updateButtonController = false
    },
    closeBlackList(formName){
      this.$refs[formName].resetFields();
      this.blackListButtonController = false
    },
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.elegant-room-table {
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  overflow: hidden;

  &::before {
    display: none;
  }

  .price-tag {
    display: inline-block;
    padding: 3px 8px;
    color: #171717;
    border-radius: 12px;
    font-weight: 500;
  }
}
</style>
